import React, { memo, useEffect, useState } from 'react'
import axios from 'axios'
import 'nanoid'
import { nanoid } from 'nanoid'
const Shops = memo(() => {
    let [list,useshop]=useState([])
    useEffect(()=>{
        axios.get('http://localhost:3000/shop').then(res=>{useshop(res.data)})
    },[])
    // 加
    function jia(id){
    let res=  list.find(item=>{
       return  item.id===id
        })
        res.miao+=1
        
      axios.put(`http://localhost:3000/shop/${id}`,res).then( 
            axios.get('http://localhost:3000/shop').then(res=>{useshop(res.data)}))
    }
    // 减
    function jian(id){
      let res=  list.find(item=>{
        return  item.id===id
         })
         res.miao-=1
        
       axios.put(`http://localhost:3000/shop/${id}`,res).then( 
             axios.get('http://localhost:3000/shop').then(res=>{useshop(res.data)}))
    }
   //删除
   function del(id){
   
     axios.delete(`http://localhost:3000/shop/${id}`).then( 
           axios.get('http://localhost:3000/shop').then(res=>{useshop(res.data)})).catch(err=>err)
  }
     //添加
     function add(){
      let res={
        "name":"niuma",
        "price": "5",
         "miao": 2,
         "id":  nanoid()
      }
      axios.post(`http://localhost:3000/shop`,res).then( 
        axios.get('http://localhost:3000/shop').then(res=>{useshop(res.data)}))
    
     }
  return (
    <div>
        {list.map(item=>(
            <p key={item.id}>{item.name}￥{item.price}<button onClick={()=>jian(item.id)}>-</button>{item.miao}<button onClick={()=>jia(item.id)} >+</button>
            <button onClick={()=>del(item.id)}>删除</button>
           
            </p>

        ))}
         <button onClick={()=>add()}>添加</button>
         总价{list.reduce((pre,cur)=>{
              pre+=cur.price*cur.miao
              return pre
         },0)}
    </div>
  )
})

export default Shops